package com.mt.fpb.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mt.fpb.enums.ResponseCode;
import com.mt.fpb.mapper.InsurancePolicyMapper;
import com.mt.fpb.mapper.RegisterMapper;
import com.mt.fpb.mapper.RxEmployeeMapper;
import com.mt.fpb.mapper.UserMapper;
import com.mt.fpb.model.InsurancePolicy;
import com.mt.fpb.model.RegisterUser;
import com.mt.fpb.model.RxEmployee;
import com.mt.fpb.model.vo.CommonResult;
import com.mt.fpb.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author yu
 * @date 2021年09月27日 18:13
 */
@Slf4j
@RestController
@RequestMapping("small")//small/getEmployeeInfo
@Transactional
public class SmallAuthenticationController {


    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserMapper userMapper;

    @Resource
    private RxEmployeeMapper rxEmployeeMapper;

    @Resource
    private InsurancePolicyMapper insurancePolicyMapper;

    @Autowired
    private RegisterMapper registerMapper;

    String phoneStr= null;
    //获取登入小金库用户的实名认证信息
    @GetMapping("/getEmployeeInfo")
    public CommonResult getEmployeeInfo(String phone){
        phoneStr=phone;
        System.out.println("phoneStr:"+phoneStr);
        //查询当前登录的员工信息，获取是否有实名认证信息
        QueryWrapper<RxEmployee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone_number",phone);
        RxEmployee rxEmployee = rxEmployeeMapper.selectOne(queryWrapper);
        if(rxEmployee==null){
            return CommonResult.fail(500,"该手机号不存在");
        }
        int nameAuth = rxEmployee.getNameAuth();
        return CommonResult.success(nameAuth);
    }

    //进行实名认证的接口
    @PostMapping("/auth")
    public CommonResult auth(String name,String idCard,String phone,String code){
        String codeStr = (String) redisUtil.get(phone);
        System.out.println("从redis中拿到的验证码:"+codeStr);
        //从redis中拿到额验证码与前端传过来的验证码进行比较
        if(code.equals(codeStr)){
            //查询保单表中的信息进行认证
            QueryWrapper<InsurancePolicy> queryWrapper = new QueryWrapper<>();
            //与投保人信息进行校验
            queryWrapper.eq("name_policyholder",name);
            queryWrapper.eq("certificate_number_policyholder",idCard);
            queryWrapper.eq("phone_policyholder",phone);
            List<InsurancePolicy> list =  insurancePolicyMapper.selectList(queryWrapper);
            if(list.isEmpty()){
                //list为空就实名认证失
                System.out.println("执行list为空的步骤");
                return CommonResult.fail(500,"实名认证失败");
            }else{
                System.out.println("执行更新操作");
                String s = phoneStr;
                //更新员工表employee中的认证信息
                int result = rxEmployeeMapper.updateAuth(s);
                System.out.println("认证后的更新认证信息的结果:"+result);
                return CommonResult.success("实名认证成功");
            }

        }

        return CommonResult.fail(ResponseCode.FAILED);

    }

   /* @ResponseBody
    @GetMapping("/isValidation")
    public CommonResult isValidation(String openId) {
        int nameAuth = 0;
        try {
            List<RegisterUser> registerUserList = registerMapper.getNameAuthByOpenId(openId);
            if (registerUserList.size() > 0) {
                nameAuth = 1;
            }else {
                nameAuth = 0;
            }
        }catch (Exception e) {
            nameAuth = 0;
        }
        System.out.println("数据库nameAuth信息:" + nameAuth);
        return CommonResult.success(nameAuth);
    }*/

    @ResponseBody
    @PostMapping("/nameValidation")
    public CommonResult nameValidation(String openId, String name, String certificateNumber, String phone, String code) {
        log.info("获取到的openId：" + openId);
        log.info("获取到的name：" + name);
        log.info("获取到的certificateNumber：" + certificateNumber);
        log.info("获取到的phone：" + phone);
        log.info("获取到的code：" + code);

        //1 验证code
        String msCode = (String) redisUtil.get(phone);
        System.out.println("后台redis存储的msCode:" + msCode);
        if (code == null && "".equals(code) && msCode == null && "".equals(msCode)) {
            log.info("短信验证码code获取失败");
            return CommonResult.fail(500, "验证码错误");
        }
        if (!msCode.equals(code)) {
            log.info("短信验证码匹配验证失败");
            return CommonResult.fail(500, "验证码错误");
        }

        //验证码验证通过，开始检查名字，身份证号，手机号是否在保单表中
        log.info("验证码验证通过，开始检查名字，身份证号，手机号是否在保单表中");
        QueryWrapper<InsurancePolicy> queryWrapper = new QueryWrapper();
        queryWrapper.eq("name_policyholder", name);
        queryWrapper.eq("certificate_number_policyholder", certificateNumber);
        queryWrapper.eq("phone_policyholder", phone);
        List<InsurancePolicy> insurancePolicyList = insurancePolicyMapper.selectList(queryWrapper);
        if (insurancePolicyList != null && !insurancePolicyList.isEmpty()) {
            log.info("实名认证成功，即将改变user表中的认证状态和身份证");
            try {
                userMapper.updataNameAuthAndIdCard(openId, certificateNumber);
            } catch (Exception e) {
                log.info("user表中的认证状态更改失败" + e.getMessage());
                return CommonResult.fail(500, "实名认证失败");
            }
        } else {
            log.info("保单表中查找不到相关信息，认证失败");
            return CommonResult.fail(500, "无匹配信息");
        }
        return CommonResult.success("实名认证成功");
    }

}
